from django.test import TestCase
from database.metric import parse_time, MetricConnection
from database import metric_conn

import json
from datetime import datetime, timedelta
import os

class MetricTestCase(TestCase):
    def test_parse_time(self):
        pass
    
    def test_MetricConnection_init(self):
        config = {
            "url": "http://1.92.152.201:9090",
        }
        # 连接成功
        connection_success = MetricConnection(config)
        self.assertIsNotNone(connection_success.client)
    
    def test_MetricConnection_all_metrics(self):
        with open("./api/tests/metric.json", "r") as f:
            data = json.load(f)
        self.assertEqual(metric_conn.all_metrics(), data["all_metrics"])
    
    def test_MetricConnection_query_range(self):
        pod = 'cartservice'
        start_time = datetime(2024, 5, 19, 1, 0, 0)
        end_time = datetime(2024, 5, 19, 1, 0, 1)

        # 1. metric_name.endswith("_total") and metric_name in self.config["network_metrics"]
        metric_name1 = "container_network_receive_packets_dropped_total"
        result1 = [{'time': datetime(2024, 5, 19, 1, 0), 'value': 0.0}, {'time': datetime(2024, 5, 19, 1, 0, 1), 'value': 0.0}]
        self.assertEqual(metric_conn.query_range(metric_name1, pod, start_time, end_time), result1)
        # 2. metric_name.endswith("_total") and metric_name not in self.config["network_metrics"]
        metric_name2 = "container_cpu_usage_seconds_total"
        result2 = [{'time': datetime(2024, 5, 19, 1, 0), 'value': 0.009}, {'time': datetime(2024, 5, 19, 1, 0, 1), 'value': 0.009}]
        self.assertEqual(metric_conn.query_range(metric_name2, pod, start_time, end_time), result2)
        # 3. not metric_name.endswith("_total") and metric_name in ['', '', ''] and metric_name in self.config["network_metrics"]
        # 不存在
        # 4. not metric_name.endswith("_total") and metric_name in ['', '', ''] and metric_name not in self.config["network_metrics"]
        metric_name3 = "container_last_seen"
        result3 = [{'time': datetime(2024, 5, 19, 1, 0), 'value': 1.0}, {'time': datetime(2024, 5, 19, 1, 0, 1), 'value': 1.0}]
        self.assertEqual(metric_conn.query_range(metric_name3, pod, start_time, end_time), result3)
        # 5. len(data_raw) == 0
        metric_name4 = 'error'
        result4 = {'error': 'No data found for metric error and pod cartservice'}
        self.assertEqual(metric_conn.query_range(metric_name4, pod, start_time, end_time), result4)
    
    def test_MetricConnection_get_query_data(self):
        start_time = datetime(2024, 5, 19, 1, 0, 0, 1)
        end_time = datetime(2024, 5, 19, 1, 0, 1, 2)

        with open("./api/tests/metric.json", "r") as f:
            data = json.load(f)["get_query_data"]
        
        result = metric_conn.get_query_data(start_time, end_time)
        exec_result = []
        for df in result:
            exec_result.append(df.to_json(orient='records'))

        self.assertEqual(exec_result, data)
    
    def test_MetricConnection_metric_extract(self):
        start_time = datetime(2024, 5, 19, 1, 0, 0, 1)
        end_time = datetime(2024, 5, 19, 1, 0, 1, 2)

        with open("./api/tests/metric.json", "r") as f:
            data = json.load(f)["metric_extract"]

        exec_result = metric_conn.metric_extract(start_time, end_time).to_json()

        self.assertEqual(exec_result, data)
    
    def test_MetricConnection_export_all_metrics(self):
        start_time = datetime(2024, 5, 19, 1, 0, 0, 1)
        end_time = datetime(2024, 5, 19, 1, 0, 1, 2)

        metric_conn.export_all_metrics(start_time, end_time, "./api/tests/metric")
        with open("./api/tests/metric.json", "r") as f:
            data = json.load(f)["get_query_data"]
        
        # 统计文件数量并删除临时目录
        csv_count = 0
        for entry in os.listdir('./api/tests/metric/'):
            if entry.lower().endswith('.csv'):
                csv_count += 1
        if os.path.exists("./api/tests/metric/"):
            os.system("rm -rf ./api/tests/metric/")

        self.assertEqual(len(data), csv_count)